import init from '@feidao/web/framework/browser/d/component';
import { id, spaceid, systemid, refsystemid } from './config';
import {
	IFeidaoAiBrowserComponent
} from '@feidao/web/interfaces';
import storage_get from '@feidao/web/atom/browser/storage/get';
import storage_clear from '@feidao/web/atom/browser/storage/clear';
import ui_get_dom_by_id from '@feidao/web/atom/browser/ui/get-dom-by-id';
import ui_set_html from '@feidao/web/atom/browser/ui/set-html';
import user_loginout from '@feidao/web/atom/browser/msg/user-logout';
import url_redirect from '@feidao/web/atom/browser/url/direct-to'
import fire from '@feidao/web/atom/browser/msg/fire';
import { file_url } from './config';
function ui_set_src(fd: IFeidaoAiBrowserComponent, node: HTMLImageElement, url: string) {
	node.src = file_url + 'getfile?productid=' + fd.data.spaceid + '&id=' + url;
}

const actions = {
	async init(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		const name = fd.data.node.getAttribute('data-feidao-name'); fd.data.node.querySelector('[data-feidao-id="name"]').innerHTML = name;

	

		const g_a = ui_get_dom_by_id(fd.data.node, 'avatar') as HTMLImageElement;
		const userInfo = await storage_get('user');
		if (userInfo) {
			if (userInfo.avatar_path) {
				await ui_set_src(fd, g_a, userInfo.avatar_path);
			} else {
				g_a.src = "./images/avatar.png"
			}

			const g_d = ui_get_dom_by_id(fd.data.node, 'user_name');
			await ui_set_html(g_d, userInfo.user_name);
		} else {
			g_a.src = "./images/m=logo.jpg"

		}

	},
	async user_loginout(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		const userInfo = await storage_get('user');
		try {
			await user_loginout(fd.data.spaceid, fd.data.systemid, userInfo);
			await storage_clear('global');
			await storage_clear();
		} catch (error) {
			console.log(error)

		} finally {
			url_redirect('login.html', {});
		}
	},
	async select_role(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		await fire('zjc-000005', 'cmpt_show');
	},
	async update_pwd(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		await fire('zjc-000006', 'cmpt_show');
	}
};

const s = {
	'fd-events-init': 'init',
	'user_loginout': 'user_loginout',
	'select_role': 'select_role',
	'update_pwd': 'update_pwd',
};

export default function main(url: string, query: any) {

	return init(id, s, actions, url, query, { spaceid, systemid, refsystemid });
}
